package com.luo.controller;

import com.alibaba.fastjson.JSON;
import com.luo.model.Goods;
import com.luo.model.OneClass;
import com.luo.model.Result;
import com.luo.model.TwoClass;
import com.luo.service.ClassService;
import com.luo.service.GoodService;
import org.aspectj.weaver.ast.Var;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/1/19 16:22
 */
@WebServlet("/updateClass")
public class ClassUpdateController extends HttpServlet {

    ClassService classService = new ClassService();
    GoodService goodService = new GoodService();
    Result result = new Result();

    @Override
    protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");
        String name = req.getParameter("name");
        String picture = req.getParameter("picture");
        String id = req.getParameter("id");
        if ("one".equals(type)) {
            OneClass oneClass = new OneClass();
            oneClass.setId(Integer.parseInt(id));
            oneClass.setPicture(picture);
            oneClass.setName(name);
            int i = classService.updateOneClass(oneClass);
            result.setCode("" + i);
            result.setMsg("修改成功");
            String jsonString = JSON.toJSONString(result);
            resp.getWriter().write(jsonString);
            resp.getWriter().close();
            return;
        } else if ("two".equals(type)) {
            //判断该分类下是否有商品
            List<Goods> goods = goodService.queryGoodsByTwoId(id);
            if (goods.size() > 0){
                result.setCode("-1");
                result.setMsg("【无法删除】\n有" + goods.size() + "条商品属于该分类");
                String jsonString = JSON.toJSONString(result);
                resp.getWriter().write(jsonString);
                resp.getWriter().close();
                return;
            }else{
                String oneClassId = req.getParameter("oneClassId");
                TwoClass twoClass = new TwoClass();
                twoClass.setId(Integer.parseInt(id));
                twoClass.setPicture(picture);
                twoClass.setName(name);
                twoClass.setOneClassId(oneClassId);
                int i = classService.updateTwoClass(twoClass);
                result.setCode("" + i);
                result.setMsg("修改成功");
                String jsonString = JSON.toJSONString(result);
                resp.getWriter().write(jsonString);
                resp.getWriter().close();
                return;
            }
        }
    }
}
